package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.user.model.UserInfo;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.util.AreaInfo;
import com.atguigu.gmall.user.util.BaiDuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户表 业务实现类
 *
 * @author atguigu
 * @since 2023-08-07
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     *
     * @param userInfo loginName可以是账号，邮箱，手机号
     * @param request
     * @return
     */
    @Override
    public Map<String, Object> login(UserInfo userInfo, HttpServletRequest request) {
        //1.根据用户提交账号查询用户记录-可以是登录账号，手机号，或者邮箱均可以
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getLoginName, userInfo.getLoginName());
        queryWrapper.or().eq(UserInfo::getEmail, userInfo.getLoginName());
        queryWrapper.or().eq(UserInfo::getPhoneNum, userInfo.getLoginName());
        UserInfo userDB = this.getOne(queryWrapper);
        if (userDB == null) {
            throw new RuntimeException("账户不存在！");
        }
        //2.验证用户密码是否正确
        //2.1 对用户提交密码进行md5加密得到密文
        String userEnterPwd = DigestUtils.md5DigestAsHex(userInfo.getPasswd().getBytes());
        //2.2 跟数据库中用户记录的密文进行比较
        if (!userDB.getPasswd().equals(userEnterPwd)) {
            throw new RuntimeException("密码错误！");
        }

        //3.验证通过，生成令牌 将令牌存入Redis中
        //3.1 采用UUID生成令牌 作为存入Redis 的key
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //3.2 构建存入Redis中用户信息(用户ID，用户登录设备标识(需要客户端提交)，用户登录所在城市-避免令牌被盗取，验证措施)
        JSONObject userObj = new JSONObject();
        userObj.put("id", userDB.getId());
        //获取用户IP地址
        try {
            AreaInfo area = BaiDuService.getArea(IpUtil.getIpAddress(request));
            if (area != null) {
                userObj.put("city", area.getCity());
            }
        } catch (Exception e) {
            log.error("[百度API]获取城市异常：{}", e);
        }
        //3.3 将令牌以及用户信息存入Redis
        String key = RedisConst.USER_KEY_PREFIX + token;
        redisTemplate.opsForValue().set(key, userObj, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);

        //4.按照接口文档响应登录业务数据
        Map<String, Object> mapResult = new HashMap<>();
        mapResult.put("token", token);
        mapResult.put("nickName", userDB.getNickName());
        return mapResult;
    }

    /**
     * 用户退出
     *
     * @param token
     */
    @Override
    public void logout(String token) {
        //1.构建用户登录时产生key
        String key = RedisConst.USER_KEY_PREFIX + token;
        //2.删除key
        redisTemplate.delete(key);
    }
}
